package com.turing.usdtpay.mvp.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.turing.usdtpay.R;
import com.turing.usdtpay.base.BaseActivity;
import com.turing.usdtpay.entity.OrderInfoData;
import com.turing.usdtpay.http.ApiUrl;
import com.turing.usdtpay.manager.UserManager;
import com.turing.usdtpay.mvp.contract.OrderInfoContract;
import com.turing.usdtpay.mvp.dialog.CancelOrderDialog;
import com.turing.usdtpay.mvp.dialog.ConfirmMoneyDialog;
import com.turing.usdtpay.mvp.dialog.QRDialog;
import com.turing.usdtpay.mvp.presenter.OrderInfoPresenter;
import com.turing.usdtpay.mvp.view.BaseTitleView;
import com.turing.usdtpay.utils.DateUtils;
import com.turing.usdtpay.utils.FormatUtils;
import com.turing.usdtpay.utils.LogUtils;
import com.turing.usdtpay.utils.QRCodeUtil;
import com.turing.usdtpay.utils.ToastUtils;

import java.io.IOException;
import java.io.Serializable;
import java.util.Date;

/**
 * @作者：JAY
 * @创建时间：2019/10/11 19:51
 * @描述：
 **/
public class SellOrderActivity extends Activity implements View.OnClickListener ,OrderInfoContract.View {

    private BaseTitleView mTitle;
    private ImageView mQRCode;
    private Button mCollect,mCancel,mHadCancel;
    private LinearLayout mEnlargeLayout;
    private int mSecond = 59,mMin = 1;
    private TextView mTime;
    private OrderInfoContract.Present mPresent;
    private ProgressBar mProgress;
    private String mOrder,mUrl;
    private TextView mOrderTv,mState,mProportion,mUsdt,mTotal,mDeal,mComplete,mCode;
    private CountDownTimer countDownTimer ;
    private double mRate;
    private ConfirmMoneyDialog dialog;
    private Bitmap bitmap;
    private double mMoney;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sell_order);
        initView();
        setPresenter(new OrderInfoPresenter(this));
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        OrderInfoData data = (OrderInfoData) intent.getSerializableExtra("data");
        if (data != null){
            mOrderTv.setText(data.getOrder());
            if (data.getStatus() == 0){
                mState.setText("待付款");
            }else if (data.getStatus() == 1){
                mState.setText("待收款");
            }else if (data.getStatus() == 2){
                mState.setText("已完成");
            }else if (data.getStatus() == 3){
                mState.setText("已取消");
                mCollect.setVisibility(View.GONE);
                mCancel.setVisibility(View.GONE);
                mHadCancel.setVisibility(View.VISIBLE);
            }
            mRate = (double) data.getMoney_change_usdt()/100;
            mProportion.setText(mRate+" CNY/USDT");
            mTotal.setText(FormatUtils.NoumberFromat2(((double)data.getMoney()/100))+" CNY");
            mUsdt.setText(FormatUtils.NoumberFromat8(((double)data.getMoney()/100)/mRate)+" USDT");
            mDeal.setText(data.getCount_order_num()+"");
            mComplete.setText(FormatUtils.NoumberFromat2((((double)data.getCount_over_order_num()/(double) data.getCount_order_num())*100))+"%");
            mOrder = data.getOrder();
            mMoney = (double)data.getMoney()/100;
            Date date = new Date(System.currentTimeMillis()/1000);
            Date endDate = new Date(data.getOver_time());
            double second = DateUtils.getDistanceTimeSecond(date, endDate);
            if (second == 0){
                mTime.setText(Html.fromHtml("<font color='#ff0000'>已超时</font>"));
                mCancel.setVisibility(View.VISIBLE);
            }else {
                mMin = (int) (second/60);
                mSecond = (int) (second - (mMin *60));
                startCount((long) (second *1000));
                mCancel.setVisibility(View.GONE);
            }
            if (data.getPay_type() == 2){
                mCode.setText("微信二维码");
                mUrl = ApiUrl.API_DOWNLOAD_WECHAT + UserManager.getInstance().getLoginDate().getTrader()+".jpg";
                LogUtils.d("微信 url =="+mUrl);
                Picasso.get().load(mUrl).memoryPolicy(MemoryPolicy.NO_CACHE).into(mQRCode);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            bitmap = Picasso.get().load(mUrl).get();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }else if (data.getPay_type() == 3){
                mCode.setText("支付宝二维码");
                mUrl = ApiUrl.API_DOWNLOAD_ALIPAY + UserManager.getInstance().getLoginDate().getTrader()+".jpg";
                LogUtils.d("支付宝 url =="+mUrl);
                Picasso.get().load(mUrl).memoryPolicy(MemoryPolicy.NO_CACHE).into(mQRCode);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            bitmap = Picasso.get().load(mUrl).get();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }
    }


    private void initView() {
        mTitle = (BaseTitleView) findViewById(R.id.title);
        mQRCode = (ImageView) findViewById(R.id.qr_code_iv);
        mCollect = (Button) findViewById(R.id.btn_collect);
        mEnlargeLayout = (LinearLayout) findViewById(R.id.enlarge_layout);
        mTime = (TextView) findViewById(R.id.tv_time);
        mOrderTv = (TextView) findViewById(R.id.tv_order);
        mState = (TextView) findViewById(R.id.tv_state);
        mProportion = (TextView) findViewById(R.id.tv_proportion);
        mUsdt = (TextView) findViewById(R.id.tv_usdt);
        mTotal = (TextView) findViewById(R.id.tv_total);
        mDeal = (TextView) findViewById(R.id.tv_deal);
        mComplete = (TextView) findViewById(R.id.tv_complete);
        mProgress = (ProgressBar) findViewById(R.id.progress);
        mCode = (TextView) findViewById(R.id.tv_code);
        mCancel = (Button) findViewById(R.id.btn_cancel);
        mHadCancel = (Button) findViewById(R.id.btn_had_cancel);
        mCancel.setOnClickListener(this);
        mCollect.setOnClickListener(this);
        mEnlargeLayout.setOnClickListener(this);
        mTitle.setLeftShow(true);
        mTitle.setLeftButtonListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTitle.setTitle("确认订单");

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == mCollect.getId()){
            dialog = new ConfirmMoneyDialog(this);
            dialog.setListener(new ConfirmMoneyDialog.ConfirmListener() {
                @Override
                public void onConfirm() {
                    mProgress.setVisibility(View.VISIBLE);
                    mPresent.confirmGet(SellOrderActivity.this,mOrder);
                }
            });
            dialog.show();
            dialog.setMoney(mMoney);
        }else if (v.getId() == mEnlargeLayout.getId()){
            if (bitmap != null){
                QRDialog dialog = new QRDialog(this);
                dialog.show();
                dialog.showQRCodeByBitmap(bitmap);
            }
        }else if (v.getId() == mCancel.getId()){
            CancelOrderDialog dialog = new CancelOrderDialog(this);
            dialog.setOnClickListener(new CancelOrderDialog.OnClickListener() {
                @Override
                public void onCancel() {
                    mProgress.setVisibility(View.VISIBLE);
                    mPresent.cancelOrder(SellOrderActivity.this,mOrder);
                }
            });
            dialog.show();
        }
    }

    @Override
    protected void onDestroy() {
        if (countDownTimer != null){
            countDownTimer.cancel();
            countDownTimer = null;
        }
        super.onDestroy();
    }

    @Override
    public void onSuccess(OrderInfoData data) {

    }

    @Override
    public void uploadSuccess(String url) {
    }

    @Override
    public void getSuccess() {
        mProgress.setVisibility(View.GONE);
        ToastUtils.showNormolToast(this,"收款成功");
        Intent intent = new Intent();
        intent.putExtra("order",mOrder);
        setResult(2,intent);
        finish();
    }

    @Override
    public void paySuccess() {

    }

    @Override
    public void cancelSuccess() {
        mProgress.setVisibility(View.GONE);
        ToastUtils.showNormolToast(this,"订单已取消");
        Intent intent = new Intent();
        intent.putExtra("order",mOrder);
        setResult(2,intent);
        finish();
    }

    @Override
    public void onFail(String msg) {
        mProgress.setVisibility(View.GONE);
        ToastUtils.showNormolToast(this,msg);
    }

    @Override
    public void onProgress(int progress) {

    }

    @Override
    public void setPresenter(OrderInfoContract.Present presenter) {
        mPresent = presenter;
    }

    private void startCount(long sum){
        countDownTimer = new CountDownTimer(sum,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mSecond = --mSecond ;
                if (mSecond <0){
                    mMin = mMin - 1 ;
                    mSecond = 59;
                }
                String text = "请在<font color='#ff0000'>"+mMin+"分"+mSecond+"秒</font>内确认收款";
                mTime.setText(Html.fromHtml(text));
            }

            @Override
            public void onFinish() {
                mTime.setText("倒数结束");
            }
        };
        countDownTimer.start();
    }
}
